<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/8
 * Time: 15:26
 */

namespace app\controllers;

use app\lib\BaseFunction;
use app\models\Pi;
use app\models\Staff;
use app\models\Invoice;
use app\service\OrderService;
use yii;

class InvoiceController extends ApiBaseController
{
    /**生成订单
     * @return string
     */
    public function actionGenerate()
    {
        $id = yii::$app->request->post('id');
        //判断invoice编号是否存在
        $model = new Invoice();
        $re = $model->one(['id' => $id]);
        if (!$re) {
            return json_encode(['code' => 0, 'msg' => '业务员invoice不存在']);
        }
        if ($re['invoice_id']) {
            return json_encode(['code' => 0, 'msg' => '当前记录已存在invoice']);
        }
        $service = new OrderService();
        $service->generateOrder($id);
    }

    /**
     * erpInvoice列表
     */
    public function actionList()
    {
        $where = [];
        $p = yii::$app->request->get('p') ? yii::$app->request->get('p') : 1;
        $s = yii::$app->request->get('s') ? yii::$app->request->get('s') : 15;
        $where['id'] = yii::$app->request->get('id', '');
        $where['invoice'] = trim(yii::$app->request->get('invoice'));
        $where['job_number'] = yii::$app->request->get('job_number');
        $where['customer_name'] = trim(yii::$app->request->get('customer_name'));
        $where['show_invoice'] = yii::$app->request->get('show_invoice');
        $model = new Invoice();
        if (!($this->user['role'] == 1 || $this->user['role'] == 2)) {
            $where['job_number'] = $this->user['job_number'];
        }

        $list = $model->get_invoice_list_by_job_number($p, $s, $where);

        $size = $model->get_invoice_size_by_job_number($where);

        $tmp = [];
        foreach ($list as $v) {
            $tmp[] = $v['pi_id'];
        }
        $piModel = new Pi();
        $piList = $piModel->getPi($tmp);
        foreach ($list as $k => $v) {
            if ($v['pi_id'] == 111) {
                $list[$k]['pi_id'] = '';
                continue;
            }
            foreach ($piList as $v2) {
                if ($v['pi_id'] == $v2['id']) {
                    $list[$k]['pi_id'] = $v2['pi_id'];
                }
            }
        }
        $staff_model = new Staff();
        $staffList = $staff_model->get_all_saleman();
        $old_arr = [];
        foreach ($list as $k => $v) {
            $old_arr[] = $v['id'];
        }
        foreach ($list as $k => $v) {
            foreach ($staffList as $v2) {
                if ($v['job_number'] == $v2['job_number']) {
                    $list[$k]['name'] = $v2['name'];
                }
            }
            $list[$k]['customer_info'] = \json_decode($v['customer_info'], true);
            $list[$k]['para'] = \json_decode($v['para'], true);
            $list[$k]['product_list'] = \json_decode($v['product_list'], true);
        }
        //历史版本信息
        $oldList = $model->getOlderIn($old_arr);
        return \json_encode(['list' => $list, 'oldList' => $oldList, 'total' => (int)$size]);
    }

    public function actionInfo()
    {
        $id = yii::$app->request->get('id');
        if (!is_numeric($id) || $id < 0) {
            return \json_encode(['code' => 0, 'msg' => '数据错误']);
        }
        $model = new Invoice();
        $info = $model->one(['id' => $id]);
        return \json_encode($info);
    }

    /**
     * 添加Invoice
     * 是业务员的
     */
    public function actionAdd()
    {
        $data = yii::$app->request->post('data');
        try {
            $data = \json_decode($data, true);

        } catch (\Exception $e) {
            return json_encode(['code' => 0, 'msg' => '数据错误']);
        }
        $data['job_number'] = $this->user['job_number'];
        if (isset($data['pi_id'])) {
            $piModel = new Pi();
            $info = $piModel->one('*', ['id' => $data['pi_id']]);
            if ($info) {
                $data['job_number'] = $info['job_number'];
            }
        }
        $data['number'] = $data['customer_info']['number'];
        $data['date'] = date('Y-m-d');
        $data['product_list'] = \json_encode($data['product_list']);
        $data['duty'] = \json_encode($data['duty']);
        $data['service'] = \json_encode($data['service']);
        $data['ship'] = \json_encode($data['ship']);
        $data['customer_info'] = \json_encode($data['customer_info']);
        $data['para'] = \json_encode($data['para']);
        $data['pay_show'] = \json_encode($data['pay_show']);
        $data['create_at'] = time();
        $invoice = new Invoice();
        $re = $invoice->add_invoice($data);
        $output = $re ? ['code' => 1, 'msg' => '添加成功'] : ['code' => 0, 'msg' => '添加失败,请重试'];
        return \json_encode($output);
    }

    /**
     * 更新invoice
     */
    public function actionUpdate()
    {
        if (!yii::$app->request->isPost) {
            return \json_encode(['code' => 0, 'msg' => 'method not allowed']);
        }
        $data = yii::$app->request->post('data');
        try {
            $data = \GuzzleHttp\json_decode($data, true);
        } catch (\Exception $e) {
            return \json_encode(['code' => 0, 'msg' => $e->getMessage()]);
        }

        $id = yii::$app->request->post('id');
        if (!is_numeric($id) || $id < 0) {
            return \json_encode(['code' => 0, 'msg' => '参数错误']);
        }
        //获取当前记录的最大版本
        //直接更新最新记录
        $model = new Invoice();
        $re = $model->one(['id' => $id]);
        if (!$re) {
            return \json_encode(['code' => 0, 'msg' => '记录不存在']);
        }

        if ((int)$re['pid'] != 0) {
            $id = $re['pid'];
        }

        //历史数据
        $re = $model->one(['id' => $id]);
        $insertData = $re;
        $insertData['pid'] = $re['id'];
        unset($insertData['id']);
        $version = $insertData['version'];
        $model->add_invoice($insertData);
        //更新当前数据
        //获取当前id
        $version++;
        $data['create_at'] = time();
        $data['version'] = $version;
        $re = $model->updateInvoice($data, ['id' => $id]);
        $output = $re ? ['code' => 1, 'msg' => '更新成功'] : ['code' => 0, 'msg' => '更新失败,请重试'];
        return \json_encode($output);

    }

    /**通过参数修改invoice
     * @return string
     */
    public function actionUpdateParam()
    {
        if (!yii::$app->request->isPost) {
            return \json_encode(['code' => 0, 'msg' => 'method not allowed']);
        }
        $need = ['id', 'value', 'column'];
        $data = yii::$app->request->post();
        foreach ($data as $k => $v) {
            if (!in_array($k, $need)) {
                return \json_encode(['code' => 0, 'msg' => '参数错误']);
            }
        }
        BaseFunction::check_edit_auth($this->user['role']);
        $update = [];
        $update[$data['column']] = $data['value'];
        $model = new  Invoice();
        if ($data['column'] == 'invoice_id') {
            //判断invoice存在
            $re = $model->one(['invoice_id' => $data['value']]);
            if ($re) {
                return \json_encode(['code' => 0, 'msg' => 'INVOICE已存在']);
            }
        }

        $re = $model->updateInvoice($update, ['id' => $data['id']]);
        $output = $re ? ['code' => 1, 'msg' => '修改成功'] : ['code' => 0, 'msg' => '修改失败,请重试'];
        return \json_encode($output);
    }

}